<?php
/**
 * 描述
 * Created by Paco
 * Date: 2019/1/29 Time: 16:47
 */

namespace App\Repositories\User;


use App\Models\Shop;
use App\Models\User\Indentity;
use App\Models\User\User;
use App\Repositories\Repository;
use Illuminate\Support\Facades\Hash;

class LoginRepository extends Repository
{
    protected $expired_in = 86400;

    public function login($mobile, $password = '', $pid = 0)
    {
        $pid = fixed_id($pid, false);
        $auth = $this->registerIdentity($mobile, 2, $this->getIP(), 0, $password);

        //如果密码登录则判断密码
        if (!empty($password)) {
            if (!Hash::check($password, $auth->password)) {
                return $this->respondError(10301);
            }
        }

        $token = uuid();

        if ($auth->user_id) {
            $user = User::query()->find($auth->user_id);
        } else {
            $user = $this->register($mobile, $pid);
            $auth->user_id = $user->user_id;
        }

        $data = [
            'token_type' => 'Bearer',
            'token' => $token,
            'expired_in' => $this->expired_in,
            'user_id' => fixed_id($user->user_id),
            'nick_name' => $user->nick_name,
            'avatar' => $user->avatar,
            'shop_id' => $user->shop_id
        ];

        $auth->ip = $this->getIP();
        $auth->remember_token = $token;
        $auth->keep_login = 1;
        $auth->save();

        $openid = Indentity::query()->where('user_id', $user->user_id)
            ->where('indentity_type', 1)
            ->value('indentity');

        $this->tokenCache($user, $token, 2, $auth->indentity_id, $pid, $openid);
        return $this->respondWith($data);
    }


    /**
     * 描术
     * 获取会员信息
     * @author Pako
     * @createTime 2019/3/2 10:19
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function userInfo()
    {
        $data = $this->getUser();
        if (!$data->shop_id) {
            return $this->respondError(10900);
        } else {
            $shop = Shop::query()->where('shop_id', $data->shop_id)->first();
            if ($shop->status) {
                return $this->respondError(10903);
            }
            if ($shop->checked == 0) {
                return $this->respondError(10902);
            }
            $data = json_decode(json_encode($data), true);
            $data['roles'] = ['admin'];
            return $this->respondWith($data);
        }

    }

    /**
     * 描术
     * 退出登录
     * @author Pako
     * @createTime 2019/3/2 10:19
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut()
    {
        $token = $this->getToken();
        app('phpredis')->del('token_' . $token);
        $user = $this->getUser();
        if ($user) {
            Indentity::query()->where('user_id', '=', $user->user_id)->update(['is_login' => 0]);
        }
        return $this->respondSuccess();
    }


    private function tokenCache($user, $token, $indentityType, $indentity_id, $pid = 0, $openid = '')
    {
        if ($user) {
            $data = [
                'user_id' => $user->user_id,
                'nick_name' => $user->nick_name,
                'avatar' => $user->avatar,
                'indentity_id' => $indentity_id,
                'indentity_type' => $indentityType,
                'pid' => $pid,
                'openid' => $openid,
                'shop_id' => $user->shop_id
            ];
        } else {
            $data = [
                'user_id' => '',
                'nick_name' => '',
                'avatar' => '',
                'indentity_id' => $indentity_id,
                'indentity_type' => $indentityType,
                'pid' => $pid,
                'openid' => $openid,
                'shop_id' => 0
            ];
        }
        app('phpredis')->setex('token_' . $token, $this->expired_in, json_encode($data));

    }


    private function register($mobile, $pid = 0)
    {
        try {
            $user = User::query()->where('mobile', $mobile)->first();
            if (!$user) {
//                if ($pid) {
//                    $sec_connect = User::query()->where('user_id', $pid)->value('pid');
//                }

                $data = [
                    'mobile' => $mobile,
                    'pid' => $pid,
                   // 'sec_connect' => $sec_connect,
                    'nick_name' => 'er_' . time(),
                    'avatar' => ''
                ];
                $user = User::query()->create($data);
            }
            return $user;
        } catch (\Exception $e) {
            $this->throwRespondWithMessage($e->getMessage());
             $this->throwRespondError(10700);
        }
    }


    private function registerIdentity($indentity, $indentityType, $ip, $user_id = 0, $password)
    {
        $auth = Indentity::query()->where('indentity', $indentity)->where('indentity_type', $indentityType)->first();
        if (!$auth) {
            if (!$password) {
                $password = random_keys();
            }
            $identityData = [
                'indentity' => $indentity,
                'indentity_type' => $indentityType,
                'password' => Hash::make($password),
                'ip' => $ip,
                'user_id' => $user_id
            ];
            $auth = Indentity::query()->create($identityData);
        }
        return $auth;
    }

}